package com.news;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by Administrator on 2017/7/4.
 */
public class MobShareModule extends ReactContextBaseJavaModule implements PlatformActionListener {

    private Context mContext;

    public MobShareModule(ReactApplicationContext reactContext) {
        super(reactContext);
      mContext = reactContext;
    }
    private static final String DURATION_SHORT_KEY = "SHORT";
    private static final String DURATION_LONG_KEY = "LONG";
    // 复写方法，返回常量
    @Override
    public Map<String, Object> getConstants() {
        final Map<String, Object> constants = new HashMap<>();
        constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
        constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
        return constants;
    }

    //复写方法，返回react-native中调用的 组件名
    @Override
    public String getName() {
        return "MobShareModule";
    }

    // 使用 @ReactMethod注解返回react-native中可调用的 方法
    // 如果需要回调参数个react-native，需要定义个call back
    @ReactMethod
    public void showShare(String msg , Callback callback){
        ShareUtils.showProduct(mContext,msg,"http://www.baidu.com");
        //callback的invoke方法可将结果回调给rn
        callback.invoke("接收到回调给react-native的参数......");
    }

    @ReactMethod void goLogin(){
        ShareSDK.initSDK(mContext);
        //微信
        authorize(new Wechat(mContext));
        //qq
//        authorize(new QQ(mContext));
    }

    private void authorize(Platform plat) {
        if(plat.isValid()) {
            String unionid = plat.getDb().get("unionid");
            String userId = plat.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                plat.removeAccount(true);
            }
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(false);
        plat.showUser(null);
    }


    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        Toast.makeText(mContext,"成功",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Toast.makeText(mContext,"错误",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancel(Platform platform, int i) {
        Toast.makeText(mContext,"取消",Toast.LENGTH_SHORT).show();
    }
}
